<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 佛山维亚轩科技，并保留所有权利。
 * 网站地址: http://www.vyxjj.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 */
namespace WXAPI\Controller;

use Think\Controller;
use Think\Log;
use Think\Page;
use Think\Page2;

class PayController extends BaseController
{
    public $mchId = 'KP10010635';
    public $secretKey = 'tAwFTtoYuMPLMDsyPosSebPUkfTe8LzI';

    public function kuPayApp($master_order_sn,$is_qrcode)
    {
        $notify_url = SITE_URL.'/WXAPI/pay/kuCallback';
        $apiUrl = 'https://pay.kudianvip.com/openapi/pay/kdh5pay';
        $orders = M('order')->where(['master_order_sn'=>$master_order_sn,'pay_status'=>0])->select();
        $yingshou = 0;
        foreach ($orders as $order){
            $yingshou+= ($order['order_amount'] + $order['yijia_heji']);
        }

        $ip = $this->get_client_ip();
        $randsi = date("YmdHis") . rand(1000, 9999);
//        $out_trade_no = get_order_sn();
        $array=
            [
                "mch_id"=>$this->mchId,
                "timestamp"=>time(),
                "nonce_str"=>$randsi,
                "sign_type"=>'MD5',
                "content"=>json_encode([
                    'fee'=>$yingshou*100,
                    'out_trade_no'=>$master_order_sn,
                    'body'=>'吉采采商城',
                    'client_ip'=>$ip,
                    'notify_url'=>$notify_url,
                ],JSON_UNESCAPED_UNICODE),
            ];


        $array = $this->getkuSign($array);

        $res = json_decode(self::http_post($apiUrl,$array), true);
        if($res && $res['code'] == -2001){ //支付失败重新下单到银行
            $new_master_order_sn = get_order_sn();
            M('order')->where(['master_order_sn'=>$master_order_sn,'pay_status'=>0])->save(['master_order_sn'=>$new_master_order_sn]);
            self::kuPayApp($new_master_order_sn,$is_qrcode);
        }
        //返回参数格式设计
        if (!empty($res['result'])) {
            $res_data = json_decode($res['result'], true);
            M('order')->where(['master_order_sn'=>$master_order_sn])->save(['pay_no'=>$res_data['pay_no']]);
            if ($is_qrcode) {
                redirect($res_data['url']);
            } else {
                jsonReturn(1, '下单成功', $res_data);
            }
        }


    }


    /**
     * 微信小程序支付
     */
    public function kuPayWechat($orderBody, $master_order_sn, $total_fee,$open_id)
    {
        $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
        $config_value = unserialize($paymentPlugin['config_value']);
        $user = M('users')->where(['open_id'=>$open_id])->find();
        $shopid = '';
        if($user && $user['biaoshi_xian']){
            $shopid = M('xian_shop')->where(['xian'=>$user['biaoshi_xian']])->getField('shopid');
        }

        $notify_url = SITE_URL.'/WXAPI/pay/kuCallback';
        $apiUrl = 'https://pay.kudianvip.com/openapi/pay/unifiedpay';
        $ip = $this->get_client_ip();
        $randsi = date("YmdHis") . rand(1000, 9999);
//        $out_trade_no = get_order_sn();
        $array=
            [
                "mch_id"=>$this->mchId,
                "timestamp"=>time(),
                "nonce_str"=>$randsi,
                "sign_type"=>'MD5',
                "content"=>json_encode([
                    "payment"=>'WXPAY',
                    "trade_type"=>'JSAPI',
                    'fee'=>$total_fee,
                    'out_trade_no'=>$master_order_sn,
                    'body'=>$orderBody,
                    'client_ip'=>$ip,
                    'notify_url'=>$notify_url,
                    'app_id' =>$config_value['appid'],
                    'open_id' =>$open_id,
                    "is_wxapp"=>'Y',
                    "shop_id"=>$shopid,
                    "limit_credit"=>0,
                ],JSON_UNESCAPED_UNICODE),
            ];


        $array = $this->getkuSign($array);

        $res = json_decode(self::http_post($apiUrl,$array), true);
        print_r($res);exit;
        //返回参数格式设计
        if (!empty($res['result'])) {
            $res_data = json_decode($res['result'], true);
            $order_sn = substr($master_order_sn,0,18);
            M('order')->where(['master_order_sn'=>$order_sn])->save(['pay_no'=>$res_data['pay_no']]);
            return $res_data;
        }
    }


    /**
     * 微信半屏小程序
     */
    public function kuPaySkippay($orderBody, $master_order_sn, $total_fee,$open_id){
        $user = M('users')->where(['open_id'=>$open_id])->find();
        $shopid = '';
        if($user && $user['biaoshi_xian']){
            $shopid = M('xian_shop')->where(['xian'=>$user['biaoshi_xian']])->getField('shopid');
        }

        $notify_url = SITE_URL.'/WXAPI/pay/kuCallback';
        $apiUrl = 'https://pay.kudianvip.com/openapi/pay/skippay';
        $ip = $this->get_client_ip();
        $randsi = date("YmdHis") . rand(1000, 9999);
//        $out_trade_no = get_order_sn();
        $array=
            [
                "mch_id"=>$this->mchId,
                "timestamp"=>time(),
                "nonce_str"=>$randsi,
                "sign_type"=>'MD5',
                "content"=>json_encode([
                    "payment"=>'WXPAY',
                    'fee'=>$total_fee,
                    'out_trade_no'=>$master_order_sn,
                    'body'=>$orderBody,
                    'client_ip'=>$ip,
                    'notify_url'=>$notify_url,
                    "shop_id"=>$shopid,
                ],JSON_UNESCAPED_UNICODE),
            ];


        $array = $this->getkuSign($array);

        $res = json_decode(self::http_post($apiUrl,$array), true);

        //返回参数格式设计
        if (!empty($res['result'])) {
            $res_data = json_decode($res['result'], true);
//            $res_data['app_id'] = 'wxca331b4f864e00f1';
//            $order_sn = substr($master_order_sn,0,18);
//            M('order')->where(['master_order_sn'=>$order_sn])->save(['pay_no'=>$res_data['pay_no']]);
            return $res_data;
        }
    }

    /**
     * 退款申请
     * @param $returnOrder
     */
    public function returnOrder($returnOrder)
    {
        $order = M('order')->where(['order_id'=>$returnOrder['order_id'],'pay_code'=>'weixin'])->find();
        if($order && $order['pay_status'] == 1){
            $notify_url = SITE_URL.'/WXAPI/pay/kuReturnCallback';
            $apiUrl = 'https://pay.kudianvip.com/openapi/pay/refund';
            $master_order_sn = $order['master_order_sn'];

            $orders = M('order')->where(['master_order_sn'=>$master_order_sn,'pay_code'=>'weixin','pay_status'=>1])->select();
            $order_amount = 0;
            foreach ($orders as $order){
                $order_amount+= $order['order_amount'];
            }

            $randsi = date("YmdHis") . rand(1000, 9999);
            $array=
                [
                    "mch_id"=>$this->mchId,
                    "timestamp"=>time(),
                    "nonce_str"=>$randsi,
                    "sign_type"=>'MD5',
                    "content"=>json_encode([
                        'fee'=>$order_amount*100,
                        'refund_fee'=>$returnOrder['member_goods_price']*100,
                        'pay_no'=>$orders[0]['pay_no'],
                        'out_refund_no'=>$randsi,
                        'notify_url'=>$notify_url,
                    ],JSON_UNESCAPED_UNICODE),
                ];


            $array = $this->getkuSign($array);

            $res = json_decode(self::http_post($apiUrl,$array), true);
            Log::record(json_encode($res), 'DEBUG');
            //返回参数格式设计
            if (!empty($res['result'])) {
                $res_data = json_decode($res['result'], true);
                if ($res_data && $res_data['status']) {
                    M('return_goods')->where(['id'=>$returnOrder['id']])->save(['pay_status'=>1,'out_refund_no'=>$randsi]);
                    return ['code'=>200,'msg'=>'退款申请成功'];
                }
            }else{
                return ['code'=>300,'msg'=>'退款申请失败'];
            }

        }
    }


    public function accountPaid($store)
    {
        if($store && $store['account_bank'] && $store['account_name'] && $store['bank_name']){
            $apiUrl = 'https://pay.kudianvip.com/openapi/pay/fund/accountPaid';
            $randsi = date("YmdHis") . rand(1000, 9999);
            $out_trade_no = get_order_sn();

            $array=
                [
                    "mch_id"=>$this->mchId,
                    "timestamp"=>time(),
                    "nonce_str"=>$randsi,
                    "sign_type"=>'MD5',
                    "content"=>json_encode([
                        'out_trade_no'=>$out_trade_no,
                        'account_type'=>2,
                        'account'=>$store['account_bank'],
                        'account_name'=>$store['account_name'],
                        'bank_name'=>$store['bank_name'],
                        'amount'=>$store['yingfu_price']*100,
                    ],JSON_UNESCAPED_UNICODE),
                ];

            $array = $this->getkuSign($array);

            $res = json_decode(self::http_post($apiUrl,$array), true);
            Log::record(json_encode($res), 'DEBUG');
            //返回参数格式设计
            M('account_paid_log')->add(['store_id'=>$store['store_id'],'store_name'=>$store['store_name'],'result'=>json_encode($res),'add_time'=>date('Y-m-d H:i:s',time())]);
            if (!empty($res['result'])) {
                $res_data = json_decode($res['result'], true);
                if (($res_data && $res_data['status'] == 100) || ($res_data && $res_data['status'] == 102)) {
                    return ['code'=>200,'msg'=>'转账成功','data'=>$res_data];
                }else{
                    return ['code'=>300,'msg'=>'转账失败'];
                }
            }else{
                return ['code'=>300,'msg'=>$res['msg']];
            }
        }else{
            return ['code'=>300,'msg'=>'银行卡信息不全'];
        }



    }



    public function closePay($master_order_sn)
    {
        $apiUrl = 'https://pay.kudianvip.com/openapi/pay/close';
        $randsi = date("YmdHis") . rand(1000, 9999);
        $array=
            [
                "mch_id"=>$this->mchId,
                "timestamp"=>time(),
                "nonce_str"=>$randsi,
                "sign_type"=>'MD5',
                "content"=>json_encode([
                    'out_trade_no'=>$master_order_sn,
                ],JSON_UNESCAPED_UNICODE),
            ];

        $array = $this->getkuSign($array);

        $res = json_decode(self::http_post($apiUrl,$array), true);
        print_r($res);
    }


    public function getkuSign($array)
    {
        foreach ($array as $k => $v)
        {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $buff = "";
        ksort($Parameters);
        foreach ($Parameters as $k => $v) {
            $buff .= $k . "=" . $v . "&";
        }
        $String = '';
        if (strlen($buff) > 0) {
            $String = substr($buff, 0, strlen($buff) - 1);
        }
        $String = $String . "&secret_key=" . $this->secretKey;
        //签名步骤三：MD5加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $strings = strtoupper($String);
        $array['sign'] = $strings;

        return json_encode($array);
    }


    /**
     * 支付反馈
     */
    public function kuCallback()
    {
        $result = file_get_contents("php://input");
        Log::record($result, 'DEBUG');

//        $result = '{"code":0,"msg":"成功","result":"{\"fee\":20,\"payment\":\"WXPAY\",\"body\":\"好多多商城\",\"status\":100,\"attach\":\"\",\"mch_id\":\"KP10010393\",\"pay_no\":\"600581089599226592\",\"out_trade_no\":\"202306302331414548\",\"transaction_id\":\"4200001847202306306799152893\",\"channel_transaction_id\":\"33202306300633972774100\",\"origin_fee\":20,\"received_fee\":20,\"user_pay_fee\":20,\"discount\":{\"mdiscount_fee\":0,\"ydiscount_fee\":0,\"pdiscount_fee\":0,\"m_discount_fee\":0,\"y_discount_fee\":0,\"p_discount_fee\":0},\"pay_time\":\"2023-06-30 23:39:39\",\"pay_finish_time\":\"2023-06-30 23:39:46\"}","sign":"382F41E50806D038D5B7B4914AAB5B4C","sign_type":"MD5"}';
        $result = json_decode($result, true);
        if (!empty($result['result'])) {
            $res_data = json_decode($result['result'], true);
            if ($res_data && $res_data['status'] == 100) {
                M('pay_callback_log')->add(['callback_text'=>json_encode($res_data)]);
                update_pay_status($res_data);
                echo "SUCCESS";
                return;
                die;
            }
        }

    }


    /**
     * 退款反馈
     */
    public function kuReturnCallback()
    {
        $result = file_get_contents("php://input");
        Log::record($result, 'DEBUG');
//        $result = '{"code":0,"msg":"成功","result":"{\"fee\":20,\"payment\":\"WXPAY\",\"body\":\"好多多商城\",\"status\":100,\"attach\":\"\",\"mch_id\":\"KP10010393\",\"pay_no\":\"600581089599226592\",\"out_trade_no\":\"202306302331414548\",\"transaction_id\":\"4200001847202306306799152893\",\"channel_transaction_id\":\"33202306300633972774100\",\"origin_fee\":20,\"received_fee\":20,\"user_pay_fee\":20,\"discount\":{\"mdiscount_fee\":0,\"ydiscount_fee\":0,\"pdiscount_fee\":0,\"m_discount_fee\":0,\"y_discount_fee\":0,\"p_discount_fee\":0},\"pay_time\":\"2023-06-30 23:39:39\",\"pay_finish_time\":\"2023-06-30 23:39:46\"}","sign":"382F41E50806D038D5B7B4914AAB5B4C","sign_type":"MD5"}';
        $result = json_decode($result, true);

        if (!empty($result['result'])) {
            $res_data = json_decode($result['result'], true);
            if ($res_data && $res_data['status'] == 200) {
                M('return_goods')->where(['out_refund_no'=>$res_data['out_refund_no']])->save(['pay_status'=>2]);
            }
            M('return_log')->add(['out_refund_no'=>$res_data['out_refund_no'],'result'=>json_encode($result)]);
            echo "SUCCESS";
            return;
            die;
        }

    }


    public function cs()
    {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        $randsi = date("YmdHis") . rand(1000, 9999);
        $out_trade_no = get_order_sn();
        $array=
            [
                "mch_id"=>$this->mchId,
                "timestamp"=>time(),
                "nonce_str"=>$randsi,
                "sign_type"=>'MD5',
                "content"=>json_encode([
                    'out_trade_no'=>$out_trade_no,
                    'account_type'=>1,
                    'account'=>'6228480099651706972',
                    'account_name'=>'邵富文',
                    'bank_name'=>'中国农业银行',
                    'amount'=>'10',
                ],JSON_UNESCAPED_UNICODE),
            ];
        foreach ($array as $k => $v)
        {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $buff = "";
        ksort($Parameters);
        foreach ($Parameters as $k => $v) {
            $buff .= $k . "=" . $v . "&";
        }
        $String = '';
        if (strlen($buff) > 0) {
            $String = substr($buff, 0, strlen($buff) - 1);
        }
        //签名步骤三：MD5加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $strings = strtoupper($String);
        $array['sign'] = $strings;

        $res = json_decode(self::http_post('https://pay.kudianvip.com/openapi/pay/fund/accountPaid',json_encode($array)), true);
        print_r($res);
    }




    /**
     * 使用http_post提交
     * @param $url
     * @param $params
     * @param bool $contentType
     * @return bool|mixed|string
     */
    protected function http_post($url, $params, $contentType=true)
    {

        if (function_exists('curl_init')){
            // curl方式
            $oCurl = curl_init();
            if (stripos($url, 'https://') !== FALSE){
                curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            }
            $string = $params;
            if (is_array($params)){
                $aPOST = array();
                foreach ($params as $key => $val) {
                    $aPOST[] = $key . '=' . urlencode($val);
                }
                $string = join('&', $aPOST);
            }
            curl_setopt($oCurl, CURLOPT_URL, $url);
            curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($oCurl, CURLOPT_POST, TRUE);
            //$contentType json处理
            if($contentType){
                $headers = array(
                    "Content-type: application/json;charset='utf-8'",
                );

                curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($oCurl, CURLOPT_POSTFIELDS, $params);
            }else{
                curl_setopt($oCurl, CURLOPT_POSTFIELDS, $string);
            }
            $response = curl_exec($oCurl);
            curl_close($oCurl);
            return $response;
        } elseif (function_exists('stream_context_create')) {
            // php5.3以上
            $opts = array(
                'http' => array(
                    'method' => 'POST',
                    'header' => 'Content-type: application/x-www-form-urlencoded',
                    'content' => http_build_query($params),
                )
            );
            $_opts = stream_context_get_params(stream_context_get_default());
            $context = stream_context_create(array_merge_recursive($_opts['options'], $opts));
            return file_get_contents($url, false, $context);
        }else{
            return FALSE;
        }
    }


    function get_client_ip() {
        $ip = '';
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $ip = trim($ips[0]);
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }

//    public function wxCallback()
//    {
//        libxml_disable_entity_loader(true);
//        // file_put_contents("./wx.txt", '1', FILE_APPEND);
//        $postStr = $GLOBALS['HTTP_RAW_POST_DATA']; // 这里拿到微信返回的数据结果
//		//file_put_contents("wx.txt", $postStr, FILE_APPEND);
//
//        $getData = $this->xmlstr_to_array($postStr); // 为了方便我就直接把结果转成数组，看个人爱好了
//		//校验数据是否安全
//		$tmpData = $getData;
//		unset($tmpData['sign']);
//		$sign = $this->getSign($tmpData);//本地签名
//		if ($getData['sign'] != $sign) {
//			return false;
//		}
//		//end  校验数据是否安全
//        if (($getData['total_fee']) && ($getData['result_code'] == 'SUCCESS')) {
//            $osn = trim($getData['out_trade_no']);
//			update_pay_status($osn,$pay_status = 1);
//			echo 'success';
//            return ;
//			die;
//        }
//    }

//
//    function xmlstr_to_array($xmlstr)
//    {
//        libxml_disable_entity_loader(true);
//
//        $xmlstring = simplexml_load_string($xmlstr, 'SimpleXMLElement', LIBXML_NOCDATA);
//
//        $val = json_decode(json_encode($xmlstring),true);
//
//        return $val;
//    }

//    /*
//     * 生成签名
//     */
//    function getSign($Obj)
//    {
//        $paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
//        $config_value = unserialize($paymentPlugin['config_value']);
//        foreach ($Obj as $k => $v) {
//            $Parameters[strtolower($k)] = $v;
//        }
//        // 签名步骤一：按字典序排序参数
//        ksort($Parameters);
//        $String = $this->formatBizQueryParaMap($Parameters, false);
//        // echo "【string】 =".$String."</br>";
//        // 签名步骤二：在string后加入KEY
//        $String = $String . "&key=" .  $config_value['key'];
//        // echo "<textarea style='width: 50%; height: 150px;'>$String</textarea> <br />";
//        // 签名步骤三：MD5加密
//        $result_ = strtoupper(md5($String));
//        return $result_;
//    }
//    // 将数组转成uri字符串
//    function formatBizQueryParaMap($paraMap, $urlencode)
//    {
//        $buff = "";
//        ksort($paraMap);
//        foreach ($paraMap as $k => $v) {
//            if ($urlencode) {
//                $v = urlencode($v);
//            }
//            $buff .= strtolower($k) . "=" . $v . "&";
//        }
//        $reqPar;
//        if (strlen($buff) > 0) {
//            $reqPar = substr($buff, 0, strlen($buff) - 1);
//        }
//        return $reqPar;
//    }
}